const { pool } = require("../../db");
// 递归生成嵌套数据
function generateNestedData(data, parentId) {
  const result = [];

  for (const item of data) {
    if (item.parent_id === parentId) {
      const children = generateNestedData(data, item.id);
      if (children.length > 0) {
        item.children = children;
      }
      result.push(item);
    }
  }

  return result;
}
// 获取所有菜单
exports.getAllMenu = async () => {
  const query = `select * from menus`;
  try {
    const [rows] = await pool.query(query);
    const result = generateNestedData(rows, null);
    return { code: 200, data: result };
  } catch (error) {
    return { code: 500, message: error.message };
  }
};
// 添加菜单
exports.addMenu = async (name, parent_id) => {
  const query = `Insert into menus(name,parent_id) values('${name}','${parent_id}')`;
  try {
    await pool.query(query);
    return { code: 200, message: "添加成功" };
  } catch (error) {
    return { code: 500, message: error.message };
  }
};
// 修改菜单
exports.updateMenu = async (id, name) => {
  const query = `update menus set name='${name}' where id=${id}`;
  try {
    await pool.query(query);
    return { code: 200, message: "修改成功" };
  } catch (error) {
    return { code: 500, message: error.message };
  }
};
// 删除菜单
exports.deleteMenu = async (id) => {
  const query = `delete from roles_menus where menu_id=${id};`;
  const query1 = `delete from menus where id=${id};`;
  try {
    await pool.query(query);
    await pool.query(query1);
    return { code: 200, message: "删除成功" };
  } catch (error) {
    return { code: 500, message: error.message };
  }
};
